<template>
  <div class="system-user-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="600">
      <el-form ref="formRef" :model="state.ruleForm" :rules="state.rules" size="default" label-width="100px">
        <el-form-item label="电表名称" prop="name">
          <el-input v-model="state.ruleForm.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="电表类型" prop="type">
          <CommonSelect v-model="state.ruleForm.type" :options="ElectricityMeterTypeOptions"></CommonSelect>
        </el-form-item>
        <el-form-item v-if="state.ruleForm.type !== ElectricityMeterType.GENERAL" label="父表" prop="parent_id">
          <CommonSelect
            v-model="state.ruleForm.parent_id"
            :options="state.electricityMeters"
            label-key="name"
            value-key="id"
            placeholder="请输入"
          ></CommonSelect>
        </el-form-item>
        <el-form-item label="倍率" prop="rate">
          <el-input-number v-model="state.ruleForm.rate" placeholder="请输入"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default" :loading="state.submit.loading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="electricityMeterDialog">
import { nextTick, reactive, ref, watch } from 'vue';
import { ElectricityMeter } from '/@/models';
import { DialogType } from '/@/constants/dialog-type';
import { createElectricityMeter, updateElectricityMeter, readAllElectricityMeter } from '/@/api/electricity-meter';
import { ElMessage } from 'element-plus';
import { assginDefault } from '/@/utils/assign-default';
import { cloneDeep } from 'lodash/fp';
import { createRequiredRule } from '/@/utils';
import CommonSelect from '/@/components/common-select/index.vue';
import { ElectricityMeterType, ElectricityMeterTypeLabel } from '/@/constants';
import { toOptions } from '/@/hooks/use-options';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

const ElectricityMeterTypeOptions = toOptions(ElectricityMeterTypeLabel)
// 定义变量内容
const formRef = ref();
const state = reactive({
  id: '',
  ruleForm: {
    name: '',
    rate: null,
    type: ElectricityMeterType.GENERAL,
    parent_id: null
  },
  rules: {
    name: createRequiredRule(),
    rate: createRequiredRule(),
    type: createRequiredRule(),
    parent_id: createRequiredRule()
  },
  electricityMeters: [],
  submit: {
    loading: false
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: ''
  }
});

watch(
  () => state.ruleForm.type,
  () => {
    if (state.ruleForm.type !== ElectricityMeterType.GENERAL && !state.electricityMeters.length) {
      readAllElectricityMeter({ page: 1, pageSize: 1000, type: ElectricityMeterType.GENERAL }).then((res) => {
        state.electricityMeters = res?.data?.list || [];
      });
    }
  }
);

// 打开弹窗
const openDialog = (type: string, row?: ElectricityMeter) => {
  state.dialog.type = type;
  state.dialog.isShowDialog = true;
  nextTick(() => {
    if (type === DialogType.EDIT) {
      state.id = row.id;
      assginDefault(state.ruleForm, cloneDeep(row));
      state.dialog.title = '修改电表';
    } else {
      state.id = '';
      state.dialog.title = '新增电表';
      formRef.value?.resetFields();
    }
  });
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
  closeDialog();
};

// 提交
const onSubmit = async () => {
  await formRef.value.validate();
  try {
    state.submit.loading = true;
    const data = {
      ...state.ruleForm
    };
    if (state.dialog.type === DialogType.EDIT) {
      await updateElectricityMeter(state.id, data);
    } else {
      await createElectricityMeter(data);
    }
    ElMessage.success('保存成功');
    closeDialog();
    emit('refresh');
  } catch (err) {
    console.log(err);
  }

  state.submit.loading = false;
};

// 暴露变量
defineExpose({
  openDialog,
  closeDialog
});
</script>
